package com.ninetaildemonfox.zdl.socialproject.mvp.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.easeui.utils.map.JSONUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.ninetaildemonfox.base.BaseFragment;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.data.entity.SerializableMap;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.PicturePreviewDelete;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.PicturePresenter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.PicturePreviewActivity;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;

/**
 * A simple {@link Fragment} subclass.
 */
public class PicturePFragment extends BaseFragment {

    @BindView(R.id.text_burn_after_reading)
    TextView textBurnAfterReading;
    @BindView(R.id.imageView)
    ImageView imageView;
    private Map<String, String> data;
    private String is_see;
    private Drawable drawable;
    @BindView(R.id.videoplayer)
    JZVideoPlayerStandard videoplayer;
    private PicturePresenter picturePresenter;
    public String TAG = "BlankFragment";
    public int count;
    private String cover_member_id;
    int type = 0;
    private PicturePreviewActivity picturePreviewActivity;
    private int getPoation = 0;


    @SuppressLint("HandlerLeak")
    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_picture;
    }


    @Override
    protected void onInitView(Bundle savedInstanceState) {
        picturePresenter = new PicturePresenter(fgtContext);
        switch (type) {
            case 1:
                //设置
                settings();
                break;
            case 2:
                //预览
                preview();
                break;
            default:
        }
    }

    private void preview() {
        textBurnAfterReading.setVisibility(View.GONE);
        //  是否设置阅后即焚  1否 2是
        if (TextUtils.isEmpty(cover_member_id)) {
            imageView.setVisibility(View.VISIBLE);
            Glide.with(me).load(data.get("pic")).into(imageView);
        } else {
            is_see = data.get("is_see");
            if (is_see.equals("2")) {
                //   是否看过图片  1是 2否
                if (data.get("have_see").equals("1")) {
                    imageView.setImageResource(R.mipmap.icon_burned);
                } else {
                    imageView.setImageResource(R.mipmap.icon_unburnt);
                    imageView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            if (data.get("have_see").equals("1")) {
                                imageView.setImageResource(R.mipmap.icon_burned);
                            } else {
                                // 是否是视频  0否 1是
                                if (data.get("is_video").equals("1")) {
                                    videoplayer.setVisibility(View.VISIBLE);
                                    imageView.setVisibility(View.GONE);
                                    //视频
                                    if (data.get("url") != null) {
                                        //视频路径
                                        videoplayer.setUp(data.get("url"),
                                                JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,
                                                "");
//                                        Bitmap bitmap1 = returnBitMap(data.get("pic"));
                                        //图片路径
//                                        videoplayer.thumbImageView.setImageBitmap(bitmap1);
                                        videoplayer.startVideo();
                                    }
                                } else {
                                    //图片路径
                                    imageView.setVisibility(View.VISIBLE);
                                    videoplayer.setVisibility(View.GONE);
                                    Glide.with(me).load(data.get("pic")).into(imageView);
                                }
                                //图片id    被看人的id
                                picturePresenter.lookImage(token, data.get("id"), cover_member_id);
                            }
                            return true;
                        }
                    });
                    imageView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if (event.getAction() == MotionEvent.ACTION_UP) {
                                //抬起
                                imageView.setVisibility(View.VISIBLE);
                                imageView.setImageResource(R.mipmap.icon_burned);
                                data.put("have_see", "2");
                            }
                            return false;
                        }
                    });
                }
            } else {
                // 是否是视频  0否 1是
                if (data.get("is_video").equals("1")) {
                    videoplayer.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.GONE);
                    //视频
                    if (data.get("url") != null) {
                        //视频路径
                        videoplayer.setUp(data.get("url"),
                                JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,
                                "");
//                        Bitmap bitmap1 = returnBitMap(data.get("pic"));
//                        //图片路径
//                        videoplayer.thumbImageView.setImageBitmap(bitmap1);
                        videoplayer.startVideo();
                    }
                } else {
                    //图片路径
                    videoplayer.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                    Glide.with(me).load(data.get("pic")).into(imageView);
                }
            }
        }


    }

    private void settings() {
        textBurnAfterReading.setVisibility(View.VISIBLE);
        //  是否设置阅后即焚  1否 2是
        is_see = data.get("is_see");
        if (is_see.equals("2")) {
            drawable = getResources().getDrawable(R.mipmap.ic_circular_true);
        } else {
            drawable = getResources().getDrawable(R.mipmap.ic_circular_false);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textBurnAfterReading.setCompoundDrawables(drawable, null, null, null);
        // 是否是视频  0否 1是
        if (data.get("is_video").equals("1")) {
            videoplayer.setVisibility(View.VISIBLE);
            //视频
            if (data.get("url") != null) {
                //视频路径
                videoplayer.setUp(data.get("url"),
                        JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,
                        "");
//                Bitmap bitmap1 = returnBitMap(data.get("pic"));
//                //图片路径
//                videoplayer.thumbImageView.setImageBitmap(bitmap1);
                videoplayer.startVideo();
            }
        } else {
            videoplayer.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            //图片路径
            Glide.with(me).load(data.get("pic")).into(imageView);
        }
    }

    public static PicturePFragment intentFragment(Map<String, String> list, int type) {
        PicturePFragment blankFragment = new PicturePFragment();
        SerializableMap map = new SerializableMap(list);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", map);
        bundle.putInt("type", type);
        blankFragment.setArguments(bundle);
        return blankFragment;
    }

    public static PicturePFragment intentFragment(Map<String, String> list, int type, String cover_member_id) {
        PicturePFragment blankFragment = new PicturePFragment();
        SerializableMap map = new SerializableMap(list);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", map);
        bundle.putInt("type", type);
        bundle.putString("cover_member_id", cover_member_id);
        blankFragment.setArguments(bundle);
        return blankFragment;
    }

    public static PicturePFragment intentFragment() {
        return new PicturePFragment();
    }

    @OnClick({R.id.text_burn_after_reading})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_burn_after_reading:
                if (is_see.equals("2")) {
                    drawable = getResources().getDrawable(R.mipmap.ic_circular_false);
                    is_see = "1";
                } else {
                    is_see = "2";
                    drawable = getResources().getDrawable(R.mipmap.ic_circular_true);
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textBurnAfterReading.setCompoundDrawables(drawable, null, null, null);
                WaitDialog.show(fgtContext, "上传中....");
                HttpRequest.POST(me, "Member/uploadImgLook"
                        , new Parameter()
                                .add("token", token)
                                .add("is_see", is_see)//设置阅后即焚 1否 2是
                                .add("type", "2")//1上传 2设置
                                .add("id", data.get("id"))  // 预览 设置是否焚毁 相册id【设置时图片或视频 id】
                        , new ResponseListener() {
                            @Override
                            public void onResponse(String response, Exception error) {
                                WaitDialog.dismiss();
                                if (error == null) {
                                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                    TipDialog.show(fgtContext, map.get("message"), TipDialog.TYPE.SUCCESS);
                                }
                            }
                        });
                break;
            default:
        }
    }

    Bitmap bitmap;

    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return bitmap;
    }

    @Override
    public void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    public void getData(Map<String, String> list, int type, String cover_member_id, int getPoation) {
        this.data = list;
        this.type = type;
        this.cover_member_id = cover_member_id;
        this.getPoation = getPoation;
    }

    //    @Override
    public void getDelete(AppCompatActivity getMe, String token, Map<String, String> list) {
        WaitDialog.show(getMe, "数据删除中");
//    删除图片
        HttpRequest.POST(getMe, "Member/delImage"
                , new Parameter()
                        .add("token", token)
                        .add("img_id", list.get("id"))
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        WaitDialog.dismiss();
                        if (error != null) {
                            return;
                        }
                        Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                        if (map == null) {
                            return;
                        }
                        if (map.get("code").equals("1")) {
                            getMe.finish();
                        }
                        ToastUtil.show(data.get("message"));
                    }
                });
    }
}
